import React, { Component } from 'react';
import List from '../list/list';
import {Link, withRouter} from 'react-router-dom';
import { Toast } from 'react-weui';
import Swiper from 'swiper/dist/js/swiper.js';
import { connect } from "react-redux";
import * as actions from '../../../store/action/homepage';
import {loadMore} from '../../../utils';
import { msg, getPrize } from '../../../api/home';
import 'swiper/dist/css/swiper.min.css';
import './home.less';

const ICON_LOTTERY = require('../../../static/images2/lottery.png');

class HomePage extends Component {
    constructor() {
        super()
        this.state = {
          searchValue: '', // 搜索输入值
          currentIndex: 0, // 目前选中的type,默认第一个
          tabList: [
            { type: '推荐1',typeid: 1},
            { type: '推荐2',typeid: 2},
            { type: '推荐3',typeid: 3},
            { type: '推荐4',typeid: 4},
            { type: '推荐5',typeid: 5},
            { type: '推荐6',typeid: 6},
            { type: '推荐7',typeid: 7},
            { type: '推荐8',typeid: 8},
            { type: '推荐9',typeid: 9},
          ],
          blocknone: false,
          bannerList: [
            {
              url: 'www.baidu.com',
              bgimg: ''
            }
          ],
          listClass: 'list-row', //列表排列样式
          listData: [ // 列表数据
            {
              image: 'https://cn.bing.com/az/hprichbg/rb/NarrowsZion_ZH-CN9686302838_1920x1080.jpg',
              logo: 'https://cn.bing.com/az/hprichbg/rb/NarrowsZion_ZH-CN9686302838_1920x1080.jpg',
              title: '测试女装大佬哇卡阿卡卡阿卡试女装大佬哇卡阿卡卡阿卡试女装大佬哇卡阿卡卡阿卡卡',
              oldprice: '30',
              salenumber:'111111',
              newprice:'20',
              coupon:'10'
            },
            {
              image: 'https://cn.bing.com/az/hprichbg/rb/NarrowsZion_ZH-CN9686302838_1920x1080.jpg',
              logo: 'https://cn.bing.com/az/hprichbg/rb/NarrowsZion_ZH-CN9686302838_1920x1080.jpg',
              title: '测试女装大佬哇卡阿卡卡阿试女装大佬哇卡阿卡卡阿卡试女装大佬哇卡阿卡卡阿卡卡卡',
              oldprice: '30',
              salenumber:'111111',
              newprice:'20',
              coupon:'10'
            },
            {
              image: 'https://cn.bing.com/az/hprichbg/rb/NarrowsZion_ZH-CN9686302838_1920x1080.jpg',
              logo: 'https://cn.bing.com/az/hprichbg/rb/NarrowsZion_ZH-CN9686302838_1920x1080.jpg',
              title: '测试女装大佬哇卡阿卡卡阿试女装大佬哇卡阿卡卡阿卡试女装大佬哇卡阿卡卡阿卡卡卡',
              oldprice: '30',
              salenumber:'111111',
              newprice:'20',
              coupon:'10'
            },
            {
              image: 'https://cn.bing.com/az/hprichbg/rb/NarrowsZion_ZH-CN9686302838_1920x1080.jpg',
              logo: 'https://cn.bing.com/az/hprichbg/rb/NarrowsZion_ZH-CN9686302838_1920x1080.jpg',
              title: '测试女装大佬哇卡阿卡卡试女装大佬哇卡阿卡卡阿卡试女装大佬哇卡阿卡卡阿卡阿卡卡',
              oldprice: '30',
              salenumber:'111111',
              newprice:'20',
              coupon:'10'
            },
            {
              image: 'https://cn.bing.com/az/hprichbg/rb/NarrowsZion_ZH-CN9686302838_1920x1080.jpg',
              logo: 'https://cn.bing.com/az/hprichbg/rb/NarrowsZion_ZH-CN9686302838_1920x1080.jpg',
              title: '测试女装大佬哇卡阿卡卡试女装大佬哇卡阿卡卡阿卡试女装大佬哇卡阿卡卡阿卡阿卡卡',
              oldprice: '30',
              salenumber: '111111',
              newprice: '20',
              coupon: '888',
              id: 1
            }
          ],
          count: 0
        }
        // bind prize
        this.onPrize = this.onPrize.bind(this);
    }
    swiper2() {
      new Swiper('.my-swiper2', {
        autoplay: true,
        loop: true,
        observer: true,
        observeParents: true,
        direction : 'vertical',
      });
    }
    componentWillMount(){
      // if(!this.props.homepage.fetched){
        this.props.fetchHome();
        // this.props.fetchPrize(1);

        
        // console.log(this.props)
      // }
    }
    // 组件挂载
    componentDidMount () {
      loadMore(this.mainContent,this.props.fetchHome);
      // 生成swiper对象
      setTimeout(function(){
        new Swiper('.my-swiper1', {
          autoplay: true,
          loop: true,
          observer: true,
          observeParents: true,
          pagination : {
              el: '.swiper-pagination',
          }
        });
      })
      
      this.swiper2();
    }
    componentWillReceiveProps(){
      let token = localStorage.getItem('token');
      var _this = this;
      if(token){
        msg().then(resp => {
          if(resp.data.count > 0){
            _this.setState({
              count: resp.data.count
            })
          }
        })
      }
    }
    // 搜索
    changeSearch(e) {
      this.setState({
        searchValue : e.target.value
      })
    }
    // enter触发搜索
    KeyUpEnter(e) {
      // 监控 enter 事件
      if (e.keyCode !== 13) {
        return
      }
      if (e.target.value) {
        // var params={
        //   keywords: e.target.value,
        //   page: 1,
        //   pagesize: 10
        // }
        // console.log(params);
        // search(params).then(resp => {
        //   console.log(resp)
        // }).catch(err => {
        //   console.log(err)
        // })
        this.props.history.push(`/categoryDetail/${e.target.value}`);
      }else {
        alert('搜索条案不能为空')
      }
    }
    // 头部类型切换
    changeType(type, index) {
      this.props.homepage.hotProducts = [];
      this.props.homepage.page = 1;
      if(index === 0) {
        this.swiper2()
      }
      if(type === 0){
        this.props.fetchHome();
      }else{
        this.props.fetchCate(type);
      }
      this.setState({
        currentIndex : index,
        blocknone : false
      })
    }
    // 头部类型切换样式加载
    activeClass(index) {
      return index === this.state.currentIndex ? 'item-title active' : 'item-title';
    }
    // 头部弹框
    showAlltype() {
      this.setState({
        blocknone : !this.state.blocknone
      })
    }
    getMsg(){
      this.props.history.push('/myMessage');
    }
    // 抽奖页
    onPrize() {
      const {
        onPrizeData
      } = this.props;
      getPrize(1).then((res) => {
        if (res.ret == 0) {
          onPrizeData(res);
          this.props.history.push('/lottery');
        } else {
          alert(res.msg);
        }
      })
      .catch((e) => {
        console.log("prize err:", e.response.data);
        if (e.response.data.ret == 999) {
          this.props.history.push('/glogin');
        } 
      })
    }
    render() {
        return (
            <div>
               {/* 搜索框区域 */}
               <div className="home-search">
                  <div className="search-input">
                    <img className="logo-search" src={require('../../../static/images2/logo-search.png')} alt="" />
                    <input
                        type="text"
                        name="phoneNumber"
                        placeholder="输入您需要的商品名称"
                        onChange={this.changeSearch.bind(this)}
                        onKeyUp={this.KeyUpEnter.bind(this)}
                        value={this.state.searchValue}
                    />
                  </div>
                  <div className="search-msg" onClick={this.getMsg.bind(this)}>
                    <img className="logo-msg" src={require('../../../static/images2/logo-msg.png')} alt="" />
                    {this.state.count > 0 ? (<span class='point'></span>): ''} 
                    <div>消息</div>
                  </div>
                </div>
                <div className="home-lottery" onClick={this.onPrize}>
                  <img src={ICON_LOTTERY} alt="" className="home-lottery-icon" />
                </div>
                <div className="home-tabbar">
                  <div className="tabbar-item">
                    {this.props.homepage.tabList.map((item, index) => {
                      return <div className={ this.activeClass(index) } onClick={this.changeType.bind(this, item.id, index)} key={index}>{item.title}</div>
                    })}
                  </div>
                  <div className="tab-all">
                    <img onClick={ this.showAlltype.bind(this) } className="logo-threeline" src={require('../../../static/images2/logo-threeline.png')} alt="" />
                  </div>
                  <div style={{ display: !this.state.blocknone ? 'none' : 'block'}} className="tab-class">
                    <div className="class-title">选择分类</div>
                    <div className="class-list">
                      {this.props.homepage.allTabList.map((item, index) => {
                        return  <div 
                                className="class-item" 
                                onClick={this.changeType.bind(this, item.id, index)} 
                                key={index}>
                                  <img src={ item.cate_img } alt=""/>
                                  <span>{item.title}</span>
                                </div>
                      })}
                    </div>
                  </div>
                  <div style={{ display: !this.state.blocknone ? 'none' : 'block'}} className="mask">
                  </div>
                </div>
               <div id="home-container" ref={ref=>this.mainContent=ref}>
                <Toast icon="loading" show={this.props.homepage.fetching}>Loading...</Toast>
                
                {/* 轮播图区域 */}
                <div className="swiper-container my-swiper1">
                  <div className="swiper-wrapper">
                    {this.props.homepage.banner.map((item, index) => {
                      return <div className="swiper-slide"><Link to={`/gDetail/${item.item_id}`}>
                        <img src={ item.images } alt=""/>
                      </Link></div>
                    })}
                  </div>
                  <div className='swiper-pagination my-pagination1'></div>
                </div>
                <Link to={`/categoryDetail`}>
                    <img className="home-img" style={{ display: this.state.currentIndex !== 0 ? 'none' : 'block'}} src={require('../../../static/images2/tuijian.png')} alt=""/>
                </Link><div style={{ display: this.state.currentIndex !== 0 ? 'none' : 'block'}} className="home-msg">
                  <div className="msg-swiper">
                    <div className="msg-title">
                      <span className="blue">消息</span>
                      <span className="red">通知</span>
                    </div>
                    <div className="swiper-container my-swiper2">
                      <div className="swiper-wrapper">
                      {this.props.homepage.officeMessage.map((item, index) => {
                        return <div className="swiper-slide my-swiper-flex">
                          <span>{ item.title }</span>
                          <img src={require('../../../static/images2/logo-fly.png')} alt=""/>
                        </div>
                      })}
                      </div>
                    </div>
                  </div>
                  <div className="msg-list">
                      <div className="list-title">
                        <span>
                          <img src={require('../../../static/images2/logo-hot.png')} alt=""/>
                          今日热销
                        </span>
                        {/* <span className="more">
                          更多
                          <img src={require('../../../static/images2/logo-right.png')} alt=""/>
                        </span> */}
                      </div>
                      <div className="list-content">
                      {this.props.homepage.todayHotProducts.map((item, index) => {
                        var url = `/gDetail/${item.item_id}`;
                        return  <Link to={url}><div className="list-item" >
                            <img src={ item.pict_url } alt=""/>
                            <div className="item-middle">
                              <span>3.5万人</span>|
                              <span>45元</span>
                            </div>
                            <div className="m-desc">{ item.item_description }</div>
                            <div className="item-price">
                              <div className="m-price">￥24</div>
                              <div className="d-line">￥69</div>
                            </div>
                          </div>
                          </Link>
                      })}
                      </div>
                  </div>
                </div>
                <div style={{ display: this.state.currentIndex === 0 ? 'none' : 'block'}} className="home-class">
                  <div className="class-list">
                    {this.props.homepage.childrenList.map((item, index) => {
                      var url = `/categoryDetail/${item.title}`;
                      return  <Link to={url}><div 
                              className="class-item" 
                              onClick={this.changeType.bind(this, item.id, index)} 
                              key={index}>
                                <img src={ item.cate_img } alt=""/>
                                <span>{ item.title }</span>
                              </div></Link>
                    })}
                  </div>
                </div>
                <div className="home-list">
                    <div className="home-list-title">
                      <img src={require('../../../static/images2/list-left.png')} alt=""/>
                      <span className="t-text">为你推荐</span>
                      <img src={require('../../../static/images2/list-right.png')} alt=""/>
                    </div>
                    <List listClass={this.state.listClass} data={this.props.homepage.hotProducts}></List>
                </div>
                
                <div className="foot-75"></div>
            </div>
            </div>
           
        )
    }
}

export default connect((state)=>{return {...state}}, actions)(HomePage);